﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;



namespace AMStudio.UserInterface
{
    public partial class NestConfigUI :Form
    {
        private int nestCfg = 0;

        public int NestCfg
        {
            get { return nestCfg; }
            set { nestCfg = value; }
        }

        public NestConfigUI()
        {
            InitializeComponent();
        }

        public NestConfigUI(int cfg)
            : this()
        {
            nestCfg = cfg;
        }
       

        private void NestConfigUI_Load(object sender, EventArgs e)
        {

            this.nestTableUI1.HoleClickEventHandler = new EventHandler<Windows.Forms.HoleEventArgs>(nestTableUI1_HoleClickEvent);

            int temp = 0;
            for (int i = 1; i < 7; i++)
            {
                temp = 1 << i;
                if ((nestCfg & temp) > 0)
                {
                    this.nestTableUI1.Status[i-1] = System.Drawing.Color.Red;
                }
                else
                {
                    this.nestTableUI1.Status[i-1] = System.Drawing.Color.Green;

                }
            }
            //this.nestTableUI1.HoleClickEvent += new EventHandler<Windows.Forms.HoleEventArgs>(nestTableUI1_HoleClickEvent);
        }

        private void nestTableUI1_HoleClickEvent(object sender, Windows.Forms.HoleEventArgs e)
        {
            //this.nestTableUI1.Status[e.SelectedItem] = !this.nestTableUI1.Status[e.SelectedItem];

            if (this.nestTableUI1.Status[e.SelectedItem-1]==System.Drawing.Color.Red)
            {
                this.nestTableUI1.Status[e.SelectedItem-1] = System.Drawing.Color.Green;
            } 
            else
            {
                this.nestTableUI1.Status[e.SelectedItem-1] = System.Drawing.Color.Red;
            }
            
            this.nestTableUI1.Invalidate();
        }


        
        private void btnSave_Click(object sender, EventArgs e)
        {
            bool[] status = new bool[7];

            for (int i = 1; i < 7;i++ )
            {
                if (this.nestTableUI1.Status[i-1] == System.Drawing.Color.Red)
                {
                    status[i] = true;
                }
            }

            nestCfg = 0;

            ConvertBooleanArrayToOneWord(status, ref nestCfg);

            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }


        private void ConvertBooleanArrayToOneWord(bool[] data, ref int dest)
        {
            if (data == null)
                return;

            int len = Math.Min(16, data.Length);

            for (int i = 0; i < len; i++)
            {
                if (data[i])
                {
                    dest += (UInt16)(1 << i);
                }
            }
        }
       
    }
}
